package classes.multithread;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author : DuJiabao
 * @Date : 2021/1/20 17:44
 * @Project : java_learning
 * @File : null.java
 * @Desc : Lock锁解决线程安全问题
 */
public class LockTest {
    public static void main(String[] args) {
        ExecutorService exec = Executors.newCachedThreadPool();
        SaleTickets3 saleTickets3 = new SaleTickets3();
        for (int i = 0; i < 3; i++) {
            exec.execute(saleTickets3);
        }
        exec.shutdown();
    }
}

class SaleTickets3 implements Runnable {
    private final ReentrantLock lock = new ReentrantLock();
    private int tickets = 100;

    @Override
    public void run() {
        while (true) {
            try {
                lock.lock(); // 调用lock方法锁住
                if (tickets > 0) {
                    System.out.println(Thread.currentThread().getName() + " " + tickets--);
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } else {
                    break;
                }
            } finally {
                lock.unlock();  // 最后一定要解锁
            }
        }
    }
}


